import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:grab_the_order/app/modules/rule/rule_controller.dart';
import 'package:grab_the_order/app/modules/rule_model.dart';
import 'package:grab_the_order/core/values/app_styles.dart';

class RuleView extends GetView<RuleController> {
  const RuleView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('抢单规则'),
        actions: [
          IconButton(
            icon: const Icon(Icons.add_circle_outline),
            onPressed: controller.showAddRuleDialog,
          ),
        ],
      ),
      body: Obx(() {
        if (controller.ruleService.rules.isEmpty) {
          return const Center(
            child: Text("暂无规则，点击右上角 '+' 添加一条吧！",
                style: TextStyle(color: Colors.grey)),
          );
        }
        return ListView.builder(
          padding: const EdgeInsets.all(8),
          itemCount: controller.ruleService.rules.length,
          itemBuilder: (context, index) {
            final rule = controller.ruleService.rules[index];
            return _buildRuleCard(rule);
          },
        );
      }),
    );
  }

  Widget _buildRuleCard(RuleModel rule) {
    return Card(
      elevation: 2,
      margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 8),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
      child: ListTile(
        contentPadding:
            const EdgeInsets.symmetric(vertical: 10, horizontal: 15),
        leading: Icon(
          rule.targetApp == TargetApp.didi
              ? Icons.local_taxi
              : Icons.delivery_dining,
          color: kPrimaryColor,
          size: 40,
        ),
        title: Text(
          "规则: ${rule.targetApp == TargetApp.didi ? '滴滴' : '美团'}",
          style: const TextStyle(fontWeight: FontWeight.bold),
        ),
        subtitle: Text(_buildRuleDescription(rule)),
        trailing: Switch(
          value: rule.isEnabled,
          onChanged: (value) {
            controller.toggleRuleStatus(rule, value);
          },
        ),
        onTap: () => controller.showEditRuleDialog(rule),
        onLongPress: () => controller.deleteRule(rule.id),
      ),
    );
  }

  String _buildRuleDescription(RuleModel rule) {
    if (rule.targetApp == TargetApp.didi) {
      List<String> conditions = [];
      if (rule.minAmount != null) {
        conditions.add("金额 > ${rule.minAmount}元");
      }
      if (rule.maxDistance != null) {
        conditions.add("路程 < ${rule.maxDistance}公里");
      }
      return conditions.isNotEmpty ? conditions.join(', ') : '无特殊条件';
    }
    return '无特殊条件';
  }
}
